/**
 *
 */
package com.wedroid.r2d2.message.handler;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wedroid.entity.contact.Contacter;
import com.wedroid.entity.contact.Droid;
import com.wedroid.entity.contact.GroupMember;
import com.wedroid.entity.message.Message;
import com.wedroid.entity.message.MessageType;
import com.wedroid.r2d2.cache.PersistentAccessor;
import com.wedroid.r2d2.contact.Contact;
import com.wedroid.r2d2.message.MessageBuilder;
import com.wedroid.r2d2.message.RipeMessage;
import com.wedroid.r2d2.service.ContactService;
import com.wedroid.r2d2.service.MessageService;

/**
 * @author lute
 */
@Component("jdbcMessageHandler")
public class JdbcMessageHandler extends AsyncMessageHandler {

    @Autowired
    private PersistentAccessor accessor;

    @Autowired
    private MessageService messageService;

    @Autowired
    private ContactService contactService;

    /* (non-Javadoc)
     * @see com.wedroid.r2d2.message.handler.AsyncMessageHandler#handleMessageInternal(com.wedroid.r2d2.message.RipeMessage)
     */
    @Override
    public void handleMessageInternal(final RipeMessage ripeMessage) {
        logger.trace("#handleMessageInternal - Handling message in JdbcMessageHandler...");

        Message message = toMessage(ripeMessage);
        messageService.createMessage(message);
    }

    /**
     * @param ripeMessage
     * @return
     */
    private Message toMessage(RipeMessage ripeMessage) {

        // Get current droid
        Contact currentDroid = ripeMessage.getDroid();
        Droid droid = accessor.getDroid(currentDroid.getNickName());
        logger.trace("#toMessage - Get droid id [{}] and nick name [{}]", droid.getId(), droid.getName());

        String content = ripeMessage.getData();
        Date messageTime = ripeMessage.getCreateTime();
        MessageType messageType = ripeMessage.getMessageType();

        Contacter sender = accessor.getContacter(droid, ripeMessage.getSender().getNickName());
        Contacter receiver = accessor.getContacter(droid, ripeMessage.getReceiver().getNickName());
        logger.trace("#toMessage - Get receiver nick name [{}]", ripeMessage.getReceiver().getNickName());

        MessageBuilder builder = new MessageBuilder(content, messageType, messageTime, droid)
                                        .msgId(ripeMessage.getMsgId())
                                        .sender(sender)
                                        .receiver(receiver);

        Contact fromUser = null;
        Contact group = null;
        if (ripeMessage.getSender().isGroup()) {
            fromUser = ripeMessage.getFromUser();
            group = ripeMessage.getSender();
        } else if (ripeMessage.getReceiver().isGroup()) {
            fromUser = ripeMessage.getSender();
            group = ripeMessage.getReceiver();
        }

        if (fromUser != null && group != null) {
            logger.trace("#toMessage - Get message from group member [{}] of group [{}]", fromUser.getNickName(), group.getNickName());

            Contacter groupContacter = accessor.getContacter(droid, group.getNickName());
            GroupMember groupMember = contactService.getGroupMember(groupContacter, fromUser.getNickName());
            if (groupMember != null) {
                builder.groupMember(groupMember);
            } else {
                logger.error("#toMessage - Can not find group member [{}] in group...", fromUser.getNickName(), ripeMessage.getSender().getNickName());
            }
        }

        return builder.build();
    }

}
